package com.hmall.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hdmall.business.common.common.Const;
import com.hdmall.business.common.common.ResponseCode;
import com.hdmall.business.common.common.ServerResponse;
import com.hdmall.business.common.util.*;
import com.hmall.mapper.*;
import com.hmall.model.*;
import com.hmall.util.EnvUtil;
import com.hdmall.business.common.util.LogUtil;
import com.hmall.vo.*;
import com.hmall.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class OrderService {


    @Autowired
    private MallOrderRemarkMapper mallOrderRemarkMapper;
    @Autowired
    private MallOrderItemDetailMapper mallOrderItemDetailMapper;

    @Autowired
    private SysCustomerMapper sysCustomerMapper;

    @Autowired
    private SysDeptCustomerMapper sysDeptCustomerMapper;

    @Autowired
    private MallOrderMapper orderMapper;

    @Autowired
    private MallOrderItemMapper orderItemMapper;

    @Autowired
    private MallCartMapper cartMapper;

    @Autowired
    private MallProductMapper mallProductMapper;

    @Autowired
    private MallProductPlanItemMapper mallProductPlanItemMapper;

    @Autowired
    private MallProductMapper productMapper;

    @Autowired
    private MallShippingMapper shippingMapper;

    @Autowired
    private MallPriceMapper priceMapper;

    @Autowired
    MallDistmodeMapper distmodeMapper;

    @Autowired
    private CartService cartService;


    @Autowired
    private MallFreightMapper mallFreightMapper;

    @Autowired
    private SysCustomerStatementMapper sysCustomerStatementMapper;

    @Autowired
    private SysUserDeptMapper sysUserDeptMapper;

    @Autowired
    private SysUserMapper userMapper;


    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private MallOrderFufillmentParentMapper mallOrderFufillmentParentMapper;

    @Autowired
    private MallOrderFufillmentMapper mallOrderFufillmentMapper;

    @Autowired
    MallPaymentVoucherMapper mallPaymentVoucherMapper;

    @Autowired
    MallAttrValueMapper mallAttrValueMapper;

    @Autowired
    MallOrderItemMapper mallOrderItemMapper;

    @Autowired
    MallOrderMapper mallOrderMapper;

    @Autowired
    SysCustomerCreditMapper sysCustomerCreditMapper;

    @Autowired
    MallPaymentUnpayMapper mallPaymentUnpayMapper;

    @Autowired
    MallTransportMapper mallTransportMapper;

    @Autowired
    DictionMapper dictionMapper;

    //修改订单状态
    public ServerResponse updateStatus(Long orderNo,Integer status){
        try{
            int update=orderMapper.updateByOrderNo(status,orderNo);
        }catch (Exception e){
            ServerResponse.createByStatus(ResponseCode.ORDER_UPDATE_ERROR.getCode(),ResponseCode.ORDER_UPDATE_ERROR.getDesc(),null);
        }
        return ServerResponse.createBySuccess("订单状态修改成功");
    }


    public ServerResponse refund(String merId,String txnAmt,String origQryId)throws ServletException,IOException{
        Map<String, String> data = new HashMap<String, String>();

        /***银联全渠道系统，产品参数，除了encoding自行选择外其他不需修改***/
        data.put("version", DemoBase.version);               //版本号
        data.put("encoding", DemoBase.encoding);             //字符集编码 可以使用UTF-8,GBK两种方式
        data.put("signMethod", SDKConfig.getConfig().getSignMethod()); //签名方法
        data.put("txnType", "04");                           //交易类型 04-退货
        data.put("txnSubType", "00");                        //交易子类型  默认00
        data.put("bizType", "000202");                       //业务类型
        data.put("channelType", "07");                       //渠道类型，07-PC，08-手机

        /***商户接入参数***/
        data.put("merId", merId);                //商户号码，请改成自己申请的商户号或者open上注册得来的777商户号测试
        data.put("accessType", "0");                         //接入类型，商户接入固定填0，不需修改
        data.put("orderId", DemoBase.getOrderId());          //商户订单号，8-40位数字字母，不能含“-”或“_”，可以自行定制规则，重新产生，不同于原消费
        data.put("txnTime", DemoBase.getCurrentTime());      //订单发送时间，格式为YYYYMMDDhhmmss，必须取当前时间，否则会报txnTime无效
        data.put("currencyCode", "156");                     //交易币种（境内商户一般是156 人民币）
        data.put("txnAmt", txnAmt);                          //****退货金额，单位分，不要带小数点。退货金额小于等于原消费金额，当小于的时候可以多次退货至退货累计金额等于原消费金额
        data.put("backUrl", DemoBase.backUrl);               //后台通知地址，后台通知参数详见open.unionpay.com帮助中心 下载  产品接口规范  网关支付产品接口规范 退货交易 商户通知,其他说明同消费交易的后台通知

        /***要调通交易以下字段必须修改***/
        data.put("origQryId", origQryId);      //****原消费交易返回的的queryId，可以从消费交易后台通知接口中或者交易状态查询接口中获取

        // 请求方保留域，
        // 透传字段，查询、通知、对账文件中均会原样出现，如有需要请启用并修改自己希望透传的数据。
        // 出现部分特殊字符时可能影响解析，请按下面建议的方式填写：
        // 1. 如果能确定内容不会出现&={}[]"'等符号时，可以直接填写数据，建议的方法如下。
//		data.put("reqReserved", "透传信息1|透传信息2|透传信息3");
        // 2. 内容可能出现&={}[]"'符号时：
        // 1) 如果需要对账文件里能显示，可将字符替换成全角＆＝｛｝【】“‘字符（自己写代码，此处不演示）；
        // 2) 如果对账文件没有显示要求，可做一下base64（如下）。
        //    注意控制数据长度，实际传输的数据长度不能超过1024位。
        //    查询、通知等接口解析时使用new String(Base64.decodeBase64(reqReserved), DemoBase.encoding);解base64后再对数据做后续解析。
//		data.put("reqReserved", Base64.encodeBase64String("任意格式的信息都可以".toString().getBytes(DemoBase.encoding)));

        /**请求参数设置完毕，以下对请求参数进行签名并发送http post请求，接收同步应答报文------------->**/

        Map<String, String> reqData  = AcpService.sign(data,DemoBase.encoding);//报文中certId,signature的值是在signData方法中获取并自动赋值的，只要证书配置正确即可。
        String url = SDKConfig.getConfig().getBackRequestUrl();								//交易请求url从配置文件读取对应属性文件acp_sdk.properties中的 acpsdk.backTransUrl
        Map<String, String> rspData = AcpService.post(reqData, url,DemoBase.encoding);//这里调用signData之后，调用submitUrl之前不能对submitFromData中的键值对做任何修改，如果修改会导致验签不通过

        /**对应答码的处理，请根据您的业务逻辑来编写程序,以下应答码处理逻辑仅供参考------------->**/
        //应答码规范参考open.unionpay.com帮助中心 下载  产品接口规范  《平台接入接口规范-第5部分-附录》
        if(!rspData.isEmpty()){
            if(AcpService.validate(rspData, DemoBase.encoding)){
                LogUtil.writeLog("验证签名成功");
                String respCode = rspData.get("respCode") ;
                if(("00").equals(respCode)){
                    //交易已受理(不代表交易已成功），等待接收后台通知更新订单状态,也可以主动发起 查询交易确定交易状态。
                    //TODO
                }else if(("03").equals(respCode)||
                        ("04").equals(respCode)||
                        ("05").equals(respCode)){
                    //后续需发起交易状态查询交易确定交易状态
                    //TODO
                }else{
                    //其他应答码为失败请排查原因
                    //TODO
                }
            }else{
                LogUtil.writeErrorLog("验证签名失败");
                //TODO 检查验证签名失败的原因
            }
        }else{
            //未返回正确的http状态
            LogUtil.writeErrorLog("未获取到返回报文或返回http状态码非200");
        }
        ResponseVo res =new ResponseVo();
        res.setAccessType(rspData.get("accessType"));
        res.setBizType(rspData.get("bizType"));
        res.setCurrencyCode(rspData.get("currencyCode"));
        res.setEncoding(rspData.get("encoding"));
        res.setMerId(rspData.get("merId"));
        res.setOrderId(rspData.get("orderId"));
        res.setOrigRespCode(rspData.get("origRespCode"));
        res.setOrigRespMsg(rspData.get("origRespMsg"));
        res.setQueryId(rspData.get("queryId"));
        res.setRespCode(rspData.get("respCode"));
        res.setRespMsg(rspData.get("respMsg"));
        res.setRespTime(rspData.get("respTime"));
        res.setSettleAmt(rspData.get("settleAmt"));
        res.setSettleCurrencyCode(rspData.get("settleCurrencyCode"));
        res.setSettleDate(rspData.get("settleDate"));
        res.setSignMethod(rspData.get("signMethod"));
        res.setSignPubKeyCert(rspData.get("signPubKeyCert"));
        res.setSignature(rspData.get("signture"));
        res.setTraceNo(rspData.get("traceNo"));
        res.setTraceTime(rspData.get("traceTime"));
        res.setTxnAmt(rspData.get("txnAmt"));
        res.setTxnSubType(rspData.get("txnSubType"));
        res.setTxnTime(rspData.get("txnTime"));
        res.setTxnType(rspData.get("txnType"));
        res.setVersion(rspData.get("version"));

        return ServerResponse.createBySuccess(res);
    }

    public ServerResponse apprefund(String merId,String txnAmt,String origQryId)throws ServletException,IOException{
        Map<String, String> data = new HashMap<String, String>();

        /***银联全渠道系统，产品参数，除了encoding自行选择外其他不需修改***/
        data.put("version", DemoBase.version);               //版本号
        data.put("encoding", DemoBase.encoding);             //字符集编码 可以使用UTF-8,GBK两种方式
        data.put("signMethod", SDKConfig.getConfig().getSignMethod()); //签名方法
        data.put("txnType", "31");                           //交易类型 31-消费撤销
        data.put("txnSubType", "00");                        //交易子类型  默认00
        data.put("bizType", "000201");                       //业务类型
        data.put("channelType", "08");                       //渠道类型，07-PC，08-手机

        /***商户接入参数***/
        data.put("merId", merId);                //商户号码，请改成自己申请的商户号或者open上注册得来的777商户号测试
        data.put("accessType", "0");                         //接入类型，商户接入固定填0，不需修改
        data.put("orderId", DemoBase.getOrderId());          //商户订单号，8-40位数字字母，不能含“-”或“_”，可以自行定制规则，重新产生，不同于原消费
        data.put("txnTime", DemoBase.getCurrentTime());      //订单发送时间，格式为YYYYMMDDhhmmss，必须取当前时间，否则会报txnTime无效
        data.put("currencyCode", "156");                     //交易币种（境内商户一般是156 人民币）
        data.put("txnAmt", txnAmt);                          //****退货金额，单位分，不要带小数点。退货金额小于等于原消费金额，当小于的时候可以多次退货至退货累计金额等于原消费金额
        data.put("backUrl", DemoBase.backUrl);               //后台通知地址，后台通知参数详见open.unionpay.com帮助中心 下载  产品接口规范  网关支付产品接口规范 退货交易 商户通知,其他说明同消费交易的后台通知

        /***要调通交易以下字段必须修改***/
        data.put("origQryId", origQryId);      //****原消费交易返回的的queryId，可以从消费交易后台通知接口中或者交易状态查询接口中获取

        // 请求方保留域，
        // 透传字段，查询、通知、对账文件中均会原样出现，如有需要请启用并修改自己希望透传的数据。
        // 出现部分特殊字符时可能影响解析，请按下面建议的方式填写：
        // 1. 如果能确定内容不会出现&={}[]"'等符号时，可以直接填写数据，建议的方法如下。
//		data.put("reqReserved", "透传信息1|透传信息2|透传信息3");
        // 2. 内容可能出现&={}[]"'符号时：
        // 1) 如果需要对账文件里能显示，可将字符替换成全角＆＝｛｝【】“‘字符（自己写代码，此处不演示）；
        // 2) 如果对账文件没有显示要求，可做一下base64（如下）。
        //    注意控制数据长度，实际传输的数据长度不能超过1024位。
        //    查询、通知等接口解析时使用new String(Base64.decodeBase64(reqReserved), DemoBase.encoding);解base64后再对数据做后续解析。
//		data.put("reqReserved", Base64.encodeBase64String("任意格式的信息都可以".toString().getBytes(DemoBase.encoding)));

        /**请求参数设置完毕，以下对请求参数进行签名并发送http post请求，接收同步应答报文------------->**/

        Map<String, String> reqData  = AcpService.sign(data,DemoBase.encoding);//报文中certId,signature的值是在signData方法中获取并自动赋值的，只要证书配置正确即可。
        String url = SDKConfig.getConfig().getBackRequestUrl();								//交易请求url从配置文件读取对应属性文件acp_sdk.properties中的 acpsdk.backTransUrl
        Map<String, String> rspData = AcpService.post(reqData, url,DemoBase.encoding);//这里调用signData之后，调用submitUrl之前不能对submitFromData中的键值对做任何修改，如果修改会导致验签不通过

        /**对应答码的处理，请根据您的业务逻辑来编写程序,以下应答码处理逻辑仅供参考------------->**/
        //应答码规范参考open.unionpay.com帮助中心 下载  产品接口规范  《平台接入接口规范-第5部分-附录》
        if(!rspData.isEmpty()){
            if(AcpService.validate(rspData, DemoBase.encoding)){
                LogUtil.writeLog("验证签名成功");
                String respCode = rspData.get("respCode") ;
                if(("00").equals(respCode)){
                    //交易已受理(不代表交易已成功），等待接收后台通知更新订单状态,也可以主动发起 查询交易确定交易状态。
                    //TODO
                }else if(("03").equals(respCode)||
                        ("04").equals(respCode)||
                        ("05").equals(respCode)){
                    //后续需发起交易状态查询交易确定交易状态
                    //TODO
                }else{
                    //其他应答码为失败请排查原因
                    //TODO
                }
            }else{
                LogUtil.writeErrorLog("验证签名失败");
                //TODO 检查验证签名失败的原因
            }
        }else{
            //未返回正确的http状态
            LogUtil.writeErrorLog("未获取到返回报文或返回http状态码非200");
        }
        ResponseVo res =new ResponseVo();
        res.setAccessType(rspData.get("accessType"));
        res.setBizType(rspData.get("bizType"));
        res.setCurrencyCode(rspData.get("currencyCode"));
        res.setEncoding(rspData.get("encoding"));
        res.setMerId(rspData.get("merId"));
        res.setOrderId(rspData.get("orderId"));
        res.setOrigRespCode(rspData.get("origRespCode"));
        res.setOrigRespMsg(rspData.get("origRespMsg"));
        res.setQueryId(rspData.get("queryId"));
        res.setRespCode(rspData.get("respCode"));
        res.setRespMsg(rspData.get("respMsg"));
        res.setRespTime(rspData.get("respTime"));
        res.setSettleAmt(rspData.get("settleAmt"));
        res.setSettleCurrencyCode(rspData.get("settleCurrencyCode"));
        res.setSettleDate(rspData.get("settleDate"));
        res.setSignMethod(rspData.get("signMethod"));
        res.setSignPubKeyCert(rspData.get("signPubKeyCert"));
        res.setSignature(rspData.get("signture"));
        res.setTraceNo(rspData.get("traceNo"));
        res.setTraceTime(rspData.get("traceTime"));
        res.setTxnAmt(rspData.get("txnAmt"));
        res.setTxnSubType(rspData.get("txnSubType"));
        res.setTxnTime(rspData.get("txnTime"));
        res.setTxnType(rspData.get("txnType"));
        res.setVersion(rspData.get("version"));

        return ServerResponse.createBySuccess(res);
    }

    public ServerResponse query(String merId,String orderId)throws ServletException,IOException{
        Map<String, String> data = new HashMap<String, String>();

        /***银联全渠道系统，产品参数，除了encoding自行选择外其他不需修改***/
        data.put("version", DemoBase.version);                 //版本号
        data.put("encoding", DemoBase.encoding);               //字符集编码 可以使用UTF-8,GBK两种方式
        data.put("signMethod", SDKConfig.getConfig().getSignMethod()); //签名方法
        data.put("txnType", "00");                             //交易类型 00-默认
        data.put("txnSubType", "00");                          //交易子类型  默认00
        data.put("bizType", "000202");                         //业务类型

        /***商户接入参数***/
        data.put("merId", merId);                  			   //商户号码，请改成自己申请的商户号或者open上注册得来的777商户号测试
        data.put("accessType", "0");                           //接入类型，商户接入固定填0，不需修改

        /***要调通交易以下字段必须修改***/
        data.put("orderId", orderId);                 //****商户订单号，每次发交易测试需修改为被查询的交易的订单号
        data.put("txnTime", DemoBase.getCurrentTime());                 //****订单发送时间，每次发交易测试需修改为被查询的交易的订单发送时间

        /**请求参数设置完毕，以下对请求参数进行签名并发送http post请求，接收同步应答报文------------->**/

        Map<String, String> reqData = AcpService.sign(data,DemoBase.encoding);			//报文中certId,signature的值是在signData方法中获取并自动赋值的，只要证书配置正确即可。
        String url = SDKConfig.getConfig().getSingleQueryUrl();								//交易请求url从配置文件读取对应属性文件acp_sdk.properties中的 acpsdk.singleQueryUrl
        Map<String, String> rspData = AcpService.post(reqData,url,DemoBase.encoding);  //发送请求报文并接受同步应答（默认连接超时时间30秒，读取返回结果超时时间30秒）;这里调用signData之后，调用submitUrl之前不能对submitFromData中的键值对做任何修改，如果修改会导致验签不通过

        /**对应答码的处理，请根据您的业务逻辑来编写程序,以下应答码处理逻辑仅供参考------------->**/
        //应答码规范参考open.unionpay.com帮助中心 下载  产品接口规范  《平台接入接口规范-第5部分-附录》
        if(!rspData.isEmpty()){
            if(AcpService.validate(rspData, DemoBase.encoding)){
                LogUtil.writeLog("验证签名成功");
                if(("00").equals(rspData.get("respCode"))){//如果查询交易成功
                    String origRespCode = rspData.get("origRespCode");
                    if(("00").equals(origRespCode)){
                        //交易成功，更新商户订单状态
                        //TODO
                    }else if(("03").equals(origRespCode)||
                            ("04").equals(origRespCode)||
                            ("05").equals(origRespCode)){
                        //订单处理中或交易状态未明，需稍后发起交易状态查询交易 【如果最终尚未确定交易是否成功请以对账文件为准】
                        //TODO
                    }else{
                        //其他应答码为交易失败
                        //TODO
                    }
                }else if(("34").equals(rspData.get("respCode"))){
                    //订单不存在，可认为交易状态未明，需要稍后发起交易状态查询，或依据对账结果为准

                }else{//查询交易本身失败，如应答码10/11检查查询报文是否正确
                    //TODO
                }
            }else{
                LogUtil.writeErrorLog("验证签名失败");
                //TODO 检查验证签名失败的原因
            }
        }else{
            //未返回正确的http状态
            LogUtil.writeErrorLog("未获取到返回报文或返回http状态码非200");
        }

        ResponseVo res =new ResponseVo();
        res.setAccessType(rspData.get("accessType"));
        res.setBizType(rspData.get("bizType"));
        res.setCurrencyCode(rspData.get("currencyCode"));
        res.setEncoding(rspData.get("encoding"));
        res.setMerId(rspData.get("merId"));
        res.setOrderId(rspData.get("orderId"));
        res.setOrigRespCode(rspData.get("origRespCode"));
        res.setOrigRespMsg(rspData.get("origRespMsg"));
        res.setQueryId(rspData.get("queryId"));
        res.setRespCode(rspData.get("respCode"));
        res.setRespMsg(rspData.get("respMsg"));
        res.setRespTime(rspData.get("respTime"));
        res.setSettleAmt(rspData.get("settleAmt"));
        res.setSettleCurrencyCode(rspData.get("settleCurrencyCode"));
        res.setSettleDate(rspData.get("settleDate"));
        res.setSignMethod(rspData.get("signMethod"));
        res.setSignPubKeyCert(rspData.get("signPubKeyCert"));
        res.setSignature(rspData.get("signture"));
        res.setTraceNo(rspData.get("traceNo"));
        res.setTraceTime(rspData.get("traceTime"));
        res.setTxnAmt(rspData.get("txnAmt"));
        res.setTxnSubType(rspData.get("txnSubType"));
        res.setTxnTime(rspData.get("txnTime"));
        res.setTxnType(rspData.get("txnType"));
        res.setVersion(rspData.get("version"));
        System.out.println(res.toString());
        return ServerResponse.createBySuccess(res);
    }

    public ServerResponse appunionpay(Long orderNo, Integer userId,HttpServletResponse response)throws ServletException, IOException{
        Map<String, String> contentData = new HashMap<String, String>();
        MallOrder order=orderMapper.selectByUserIdAndOrderNo(userId,orderNo);
        String txnAmt0=order.getPayment().doubleValue()*100+"";
        if(txnAmt0.contains(".")){
            txnAmt0=txnAmt0.substring(0,txnAmt0.indexOf("."));
        }
        /***银联全渠道系统，产品参数，除了encoding自行选择外其他不需修改***/
        contentData.put("version", DemoBase.version);            //版本号 全渠道默认值
        contentData.put("encoding", DemoBase.encoding);     //字符集编码 可以使用UTF-8,GBK两种方式
        contentData.put("signMethod", SDKConfig.getConfig().getSignMethod()); //签名方法
        contentData.put("txnType", "01");              		 	//交易类型 01:消费
        contentData.put("txnSubType", "01");           		 	//交易子类 01：消费
        contentData.put("bizType", "000201");          		 	//填写000201
        contentData.put("channelType", "08");          		 	//渠道类型 08手机

        /***商户接入参数***/
        contentData.put("merId", "777290058158248");   		 				//商户号码，请改成自己申请的商户号或者open上注册得来的777商户号测试
        contentData.put("accessType", "0");            		 	//接入类型，商户接入填0 ，不需修改（0：直连商户， 1： 收单机构 2：平台商户）
        contentData.put("orderId", orderNo.toString());        	 	    //商户订单号，8-40位数字字母，不能含“-”或“_”，可以自行定制规则
        contentData.put("txnTime", DemoBase.getCurrentTime());		 		    //订单发送时间，取系统时间，格式为YYYYMMDDhhmmss，必须取当前时间，否则会报txnTime无效
        contentData.put("accType", "01");					 	//账号类型 01：银行卡02：存折03：IC卡帐号类型(卡介质)
        contentData.put("txnAmt", txnAmt0);						//交易金额 单位为分，不能带小数点
        contentData.put("currencyCode", "156");                 //境内商户固定 156 人民币

        // 请求方保留域，
        // 透传字段，查询、通知、对账文件中均会原样出现，如有需要请启用并修改自己希望透传的数据。
        // 出现部分特殊字符时可能影响解析，请按下面建议的方式填写：
        // 1. 如果能确定内容不会出现&={}[]"'等符号时，可以直接填写数据，建议的方法如下。
//		contentData.put("reqReserved", "透传信息1|透传信息2|透传信息3");
        // 2. 内容可能出现&={}[]"'符号时：
        // 1) 如果需要对账文件里能显示，可将字符替换成全角＆＝｛｝【】“‘字符（自己写代码，此处不演示）；
        // 2) 如果对账文件没有显示要求，可做一下base64（如下）。
        //    注意控制数据长度，实际传输的数据长度不能超过1024位。
        //    查询、通知等接口解析时使用new String(Base64.decodeBase64(reqReserved), DemoBase.encoding);解base64后再对数据做后续解析。
//		contentData.put("reqReserved", Base64.encodeBase64String("任意格式的信息都可以".toString().getBytes(DemoBase.encoding)));

        //后台通知地址（需设置为外网能访问 http https均可），支付成功后银联会自动将异步通知报文post到商户上送的该地址，【支付失败的交易银联不会发送后台通知】
        //后台通知参数详见open.unionpay.com帮助中心 下载  产品接口规范  网关支付产品接口规范 消费交易 商户通知
        //注意:1.需设置为外网能访问，否则收不到通知    2.http https均可  3.收单后台通知后需要10秒内返回http200或302状态码
        //    4.如果银联通知服务器发送通知后10秒内未收到返回状态码或者应答码非http200或302，那么银联会间隔一段时间再次发送。总共发送5次，银联后续间隔1、2、4、5 分钟后会再次通知。
        //    5.后台通知地址如果上送了带有？的参数，例如：http://abc/web?a=b&c=d 在后台通知处理程序验证签名之前需要编写逻辑将这些字段去掉再验签，否则将会验签失败
        contentData.put("backUrl", DemoBase.backUrl);

        /**对请求参数进行签名并发送http post请求，接收同步应答报文**/
        Map<String, String> reqData = AcpService.sign(contentData,DemoBase.encoding);			 //报文中certId,signature的值是在signData方法中获取并自动赋值的，只要证书配置正确即可。
        String requestAppUrl = SDKConfig.getConfig().getAppRequestUrl();								 //交易请求url从配置文件读取对应属性文件acp_sdk.properties中的 acpsdk.backTransUrl
        Map<String, String> rspData = AcpService.post(reqData,requestAppUrl,DemoBase.encoding);  //发送请求报文并接受同步应答（默认连接超时时间30秒，读取返回结果超时时间30秒）;这里调用signData之后，调用submitUrl之前不能对submitFromData中的键值对做任何修改，如果修改会导致验签不通过

        /**对应答码的处理，请根据您的业务逻辑来编写程序,以下应答码处理逻辑仅供参考------------->**/
        //应答码规范参考open.unionpay.com帮助中心 下载  产品接口规范  《平台接入接口规范-第5部分-附录》
        if(!rspData.isEmpty()){
            if(AcpService.validate(rspData, DemoBase.encoding)){
                LogUtil.writeLog("验证签名成功");
                String respCode = rspData.get("respCode") ;
                if(("00").equals(respCode)){
                    //成功,获取tn号
                    String tn = rspData.get("tn");
                    //TODO
                    return ServerResponse.createBySuccess(tn);
                }else{
                    //其他应答码为失败请排查原因或做失败处理
                    //TODO
                }
            }else{
                LogUtil.writeErrorLog("验证签名失败");
                //TODO 检查验证签名失败的原因
            }
        }else{
            //未返回正确的http状态
            LogUtil.writeErrorLog("未获取到返回报文或返回http状态码非200");
        }
        return ServerResponse.createByErrorMessage("位置错误");
    }

    public ServerResponse unionpay(Long orderNo, Integer userId,HttpServletResponse response)throws ServletException, IOException{
        Map<String,String> requestData=Maps.newHashMap();
        MallOrder order=orderMapper.selectByUserIdAndOrderNo(userId,orderNo);
        if(order.getPayment().doubleValue()==0.0){
            ServerResponse.createByStatus(ResponseCode.PAY_ORDER_PAYMENT_ZERO.getCode(),ResponseCode.PAY_ORDER_PAYMENT_ZERO.getDesc(),null);
        }
        String txnAmt0=order.getPayment().doubleValue()*100+"";
        if(txnAmt0.contains(".")){
            txnAmt0=txnAmt0.substring(0,txnAmt0.indexOf("."));
        }
        requestData.put("version", DemoBase.version);
        requestData.put("encoding", DemoBase.encoding); 	      //字符集编码，可以使用UTF-8,GBK两种方式
        requestData.put("signMethod", SDKConfig.getConfig().getSignMethod()); //签名方法
        requestData.put("txnType", "01");               			  //交易类型 ，01：消费
        requestData.put("txnSubType", "01");            			  //交易子类型， 01：自助消费
        requestData.put("bizType", "000202");           			  //业务类型 000202: B2B
        requestData.put("channelType", "07");           			  //渠道类型 固定07

        /***商户接入参数***/
        requestData.put("merId", "777290058158248");    	          			  //商户号码，请改成自己申请的正式商户号或者open上注册得来的777测试商户号
        requestData.put("accessType", "0");             			  //接入类型，0：直连商户
        requestData.put("orderId",orderNo.toString());             //商户订单号，8-40位数字字母，不能含“-”或“_”，可以自行定制规则
        requestData.put("txnTime", DemoBase.getCurrentTime());        //订单发送时间，取系统时间，格式为YYYYMMDDhhmmss，必须取当前时间，否则会报txnTime无效
        requestData.put("currencyCode", "156");         			  //交易币种（境内商户一般是156 人民币）
        requestData.put("txnAmt", txnAmt0);             			      //交易金额，单位分，不要带小数点
        requestData.put("frontUrl", DemoBase.frontUrl);
        requestData.put("backUrl", DemoBase.backUrl);
        requestData.put("payTimeout", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date().getTime() + 15 * 60 * 1000));
        Map<String, String> reqData = AcpService.sign(requestData,DemoBase.encoding);
        System.out.println("reqData="+reqData);
        String requestFrontUrl = SDKConfig.getConfig().getFrontRequestUrl();
        System.out.println("requestFrontUrl="+requestFrontUrl);
        String html = AcpService.createAutoFormHtml(requestFrontUrl,reqData,DemoBase.encoding);
        System.out.println("html="+html);
        LogUtil.writeLog("打印请求HTML，此为请求报文，为联调排查问题的依据："+html);
        return ServerResponse.createBySuccess(html);
    }

    /**
     * 创建订单
     */
    public ServerResponse<List<OrderSelectVo>> createCartOrder(Integer userId, String agent, List<OrderSelectVo> orderList,Integer dealerId, String message, Integer transportId){
        if (null==orderList||orderList.size()==0){
            return  ServerResponse.createByStatus(300,"购物中没有合适的产品，请确认是否选中或有货",null);
        }

        //批量生成订单

        Long orderNo = NumberUtil.createOrderNo(dealerId);

        List<String> cartIds= new ArrayList<String>();
        //生成订单明细
        for (OrderSelectVo order:orderList){

            order.setMessage(message);
            order.setTransportId(transportId);
            List<OrderSelectItemVo> items= order.getOrderSelectItemVos();
            if(null == items) {
                return ServerResponse.createByErrorMessage("该订单无产品，无法下单");
            }
            try {

                orderMapper.insertOrderCart(orderNo,order,dealerId);
            }catch (Exception e){
                e.printStackTrace();
                return  ServerResponse.createByStatus(300,"订单生成有误",null);
            }

            //插入明细表
            try{
                //订单要有余量

                int orderItemInst=orderItemMapper.batchInsert(orderNo,userId,items);
            }catch (Exception e){
                e.printStackTrace();
                return  ServerResponse.createByStatus(300,"订单明细有误",null);
            }
            for (OrderSelectItemVo item:items){
                Integer cartId= (Integer) cartService.selectCartIdByGrdWtPrUsr(userId,item.getProductId(),item.getWeight(),item.getGrade()).getData();
                cartIds.add(String.valueOf(cartId));
            }
        }

        if(CollectionUtils.isEmpty(cartIds)){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        //根据购物车id删除产品
        try {
            cartMapper.deleteBycartIds(cartIds);
        } catch (Exception e) {
            e.printStackTrace();
            return  ServerResponse.createByStatus(300,"删除购物车产品失败",null);
        }

        backPush(userId, orderNo, 2);
        //2018/12/21要记录购买方式和购买的设备信息
        try {
            mallOrderMapper.updateCreateReason(agent, orderNo, "购物车");
        }catch (Exception e){
            //记录失败
            log.info("记录购买方式和购买的设备信息失败");
        }
        return ServerResponse.createByStatus(300,"订单生成成功",orderList);

    }

    private OrderVo assembleOrderVo(MallOrder order, List<MallOrderItem> orderItemList){
        OrderVo orderVo = new OrderVo();
        orderVo.setOrderNo(order.getOrderNo());
        // orderVo.setPayment(order.getPayment());
        orderVo.setPaymentType(order.getPaymentType());
        orderVo.setPaymentTypeDesc(Const.PaymentTypeEnum.codeOf(order.getPaymentType()).getValue());

        orderVo.setPostage(order.getPostage());
        orderVo.setStatus(order.getStatus());
        orderVo.setStatusDesc(Const.OrderStatusEnum.codeOf(order.getStatus()).getValue());

        orderVo.setShippingId(order.getShippingId());
        MallShipping shipping = shippingMapper.selectByPrimaryKey(order.getShippingId());
        if(shipping != null){
            orderVo.setReceiverName(shipping.getReceiverName());
            orderVo.setShippingVo(assembleShippingVo(shipping));
        }

        orderVo.setPaymentTime(DateTimeUtil.dateToStr(order.getPaymentTime()));
        orderVo.setSendTime(DateTimeUtil.dateToStr(order.getSendTime()));
        orderVo.setEndTime(DateTimeUtil.dateToStr(order.getEndTime()));
        orderVo.setCreateTime(DateTimeUtil.dateToStr(order.getCreateTime()));
        orderVo.setCloseTime(DateTimeUtil.dateToStr(order.getCloseTime()));

        orderVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));


        List<OrderItemVo> orderItemVoList = Lists.newArrayList();

        for(MallOrderItem orderItem : orderItemList){
            OrderItemVo orderItemVo = assembleOrderItemVo(orderItem);
            orderItemVoList.add(orderItemVo);
        }
        orderVo.setOrderItemVoList(orderItemVoList);
        return orderVo;
    }

    private OrderItemVo assembleOrderItemVo(MallOrderItem orderItem){
        OrderItemVo orderItemVo = new OrderItemVo();
        orderItemVo.setOrderNo(orderItem.getOrderNo());
        orderItemVo.setProductId(orderItem.getProductId());
        orderItemVo.setProductName(orderItem.getProductName());
        orderItemVo.setProductImage(orderItem.getProductImage());
        orderItemVo.setCurrentUnitPrice(orderItem.getCurrentUnitPrice());
        orderItemVo.setQuantity(orderItem.getQuantity());
        orderItemVo.setTotalPrice(orderItem.getTotalPrice());

        orderItemVo.setCreateTime(DateTimeUtil.dateToStr(orderItem.getCreateTime()));
        return orderItemVo;
    }

    private ShippingVo assembleShippingVo(MallShipping shipping){
        ShippingVo shippingVo = new ShippingVo();
        shippingVo.setReceiverName(shipping.getReceiverName());
        shippingVo.setReceiverAddress(shipping.getReceiverAddress());
        shippingVo.setReceiverProvince(shipping.getReceiverProvince());
        shippingVo.setReceiverCity(shipping.getReceiverCity());
        shippingVo.setReceiverDistrict(shipping.getReceiverDistrict());
        shippingVo.setReceiverMobile(shipping.getReceiverMobile());
        shippingVo.setReceiverZip(shipping.getReceiverZip());
        shippingVo.setReceiverPhone(shippingVo.getReceiverPhone());
        return shippingVo;
    }




    public ServerResponse cancel(Integer userId, Long orderNo){
        MallOrder order  = null;
        try {
            order = orderMapper.selectByUserIdAndOrderNo(userId,orderNo);
            if (order.getStatus()==20||order.getStatus()==60){
                String params1 = "";
                String params2 = "1";
                List<MallOrderItem> list = mallOrderItemMapper.getByOrderNo(orderNo);
                for (MallOrderItem aList : list) {
                    List<MallOrderItemDetail> list1 = mallOrderItemDetailMapper.selectByItemId(aList.getId());
                    if (list1.size() == 0) {
                        return ServerResponse.createByErrorMessage(aList.getProductModel() + "产品未选择物料编码");
                    }
                    for (MallOrderItemDetail mallOrderItemDetail : list1){
                        params1 = params1 + mallOrderItemDetail.getMaterialCode() + "-" + mallOrderItemDetail.getGrade()
                                + "-" + mallOrderItemDetail.getTwisting() + "-" + mallOrderItemDetail.getColor() + "-" + mallOrderItemDetail.getMachineNo() + "-" + mallOrderItemDetail.getCheckQuantity().intValue() + ",";
                    }
                }
                params1 = params1.substring(0,params1.length()-1);
                Map map2 = new HashMap();
                map2.put("itemList",params1);
                map2.put("type",params2);
                Diction diction = dictionMapper.selectByDictionKey("wmsSwitch");
                if (diction!=null&&diction.getValue().equals("1")){
                    String s = HttpClientUtil.doPostWithParam("http://47.98.171.71:9600/wms/inventorys/batch/updateInventory",map2);
                    Gson gson = new Gson();
                    Map map3 = new HashMap();
                    map3 = gson.fromJson(s, map3.getClass());
                    if (!map3.get("code").toString().equals("200.0")){
                        return ServerResponse.createByErrorMessage(map3.get("data").toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByStatus(ResponseCode.ORDER_SELECT_ERROR.getCode(),ResponseCode.ORDER_SELECT_ERROR.getDesc(),null);
        }
        if(order == null){
            return ServerResponse.createByStatus(ResponseCode.ORDER_SELECT_NOT_ERROR.getCode(),ResponseCode.ORDER_SELECT_NOT_ERROR.getDesc(),null);
        }
        //不是未支付不能取消
        /*ORDER_EXAMINE(10,"审核中"),
                ORDER_NO_PAY(30,"未支付"),
                ORDER_NO_SALES_CONT_NO(35,"未签合同"),
                ORDER_NO_SALES_CONT_MISS(36,"合同失效"),*/
        if(order.getStatus()==ResponseCode.ORDER_EXAMINE.getCode()||order.getStatus()==ResponseCode.ORDER_NO_PAY.getCode()||order.getStatus()==ResponseCode.ORDER_NO_SALES_CONT_NO.getCode()||order.getStatus()==ResponseCode.ORDER_NO_SALES_CONT_MISS.getCode()){
            MallOrder updateOrder = new MallOrder();
            updateOrder.setId(order.getId());
            updateOrder.setStatus(ResponseCode.ORDER_CANCELED.getCode());

            int row = orderMapper.updateByPrimaryKeySelective(updateOrder);
            if(row > 0){
                return ServerResponse.createByStatus(0,"用户取消订单成功",null);
            }
            return ServerResponse.createByStatus(ResponseCode.ORDER_UPDATE_ERROR.getCode(),ResponseCode.ORDER_UPDATE_ERROR.getDesc(),null);
        }
        return ServerResponse.createByStatus(ResponseCode.ORDER_UPDATE_NO_PAY_STATUS_ERROR.getCode(),ResponseCode.ORDER_UPDATE_NO_PAY_STATUS_ERROR.getDesc(),null);
    }

    /**
     * 获取1对多的订单和订单项
     * @param status
     * @param userId
     * @param pageNo
     * @param pageSize
     * @return
     */
   public ServerResponse<PageVo> getOrderItemsList(String status,Integer userId,Integer pageNo,Integer pageSize, String orderNo, String type){

       Integer pageStart=PageUtil.getPage(pageNo,pageSize);
       int totalRecord;
       List<OrderSelectVo> orderList=null;
       List<OrderSelectVo> list= new ArrayList<OrderSelectVo>();


            Integer  tStatus = Integer.valueOf(status);
               totalRecord= orderMapper.selectOrderByThreeMonthCount(tStatus,userId, orderNo, type);
               orderList = orderMapper.selectOrderItemsByThreeMonth(tStatus, userId, pageStart,pageSize, orderNo, type);


       if (orderList==null||orderList.size()==0){
           return ServerResponse.createByStatus(ResponseCode.ORDER_SELECT_NULL.getCode(),ResponseCode.ORDER_SELECT_NULL.getDesc(),new PageVo(pageNo,pageSize,0,list));
       }




        for(OrderSelectVo order : orderList){

            order.setPayment(new BigDecimal(DecimalFormatUtrils.dataFomateTwo(order.getPayment().doubleValue())));
            List<OrderSelectItemVo> items=null;
            try {
                items=orderMapper.selectOrderItemsByOrderNo(order.getOderNo());
            } catch (Exception e) {
                e.printStackTrace();
                return ServerResponse.createByStatus(ResponseCode.ORDER_ITEM_SELECT_ERROR.getCode(),ResponseCode.ORDER_ITEM_SELECT_ERROR.getDesc(),new PageVo(pageNo,pageSize,0,list));
            }
            if(null == items){
                continue;
            }


//            //查询评论
            int commentCheck = orderMapper.selectComment(order.getOderNo());
            order.setCommentCheck(commentCheck);


            for(OrderSelectItemVo itemVos:items){
                itemVos.setCurrentPrice(new BigDecimal(DecimalFormatUtrils.dataFomateTwo(itemVos.getCurrentPrice().doubleValue())));
                itemVos.setProductTotalPrice(new BigDecimal(DecimalFormatUtrils.dataFomateTwo(itemVos.getProductTotalPrice().doubleValue())));
            }

            //2019/1/11 相同等级的要进行分组
            Multimap multimap = HashMultimap.create();
            for(OrderSelectItemVo itemVos:items){
                String grade = itemVos.getGrade();
                if(grade.contains("AA") && grade.contains("定重") && !grade.contains("不")){
                    multimap.put("AA定重-" + itemVos.getProductId(), itemVos);
                }else if(grade.contains("AA") && grade.contains("不定重")){
                    multimap.put("AA不定重-" + itemVos.getProductId(), itemVos);
                }else{
                    multimap.put(grade + "-" + itemVos.getProductId(), itemVos);
                }
            }
            List<OrderSelectItemVo> newItems = new ArrayList<>();
            for(Object obj: multimap.keys()){
                Set<OrderSelectItemVo> set = ((HashMultimap) multimap).get(obj);
                OrderSelectItemVo orderSelectItemVo = new OrderSelectItemVo();

                Iterator iter = set.iterator();

                int count = 0;
                while(iter.hasNext()) {
                    OrderSelectItemVo subOrderSelectItemVo = (OrderSelectItemVo) iter.next();

                    if(count == 0){
                        count = 1;
//                        orderSelectItemVo = subOrderSelectItemVo;
                        BeanUtils.copyProperties(subOrderSelectItemVo, orderSelectItemVo);
                        continue;
                    }
                    String str = (String)obj;
                    orderSelectItemVo.setGrade(((String) obj).split("-")[0]);
                    BigDecimal weight = orderSelectItemVo.getWeight() == null ? new BigDecimal(0) : orderSelectItemVo.getWeight();
                    BigDecimal productTotalPrice = orderSelectItemVo.getProductTotalPrice() == null ? new BigDecimal(0.0) : orderSelectItemVo.getProductTotalPrice();
                    orderSelectItemVo.setWeight(weight.add(subOrderSelectItemVo.getWeight()));
                    orderSelectItemVo.setProductTotalPrice(productTotalPrice.add(subOrderSelectItemVo.getProductTotalPrice()));
                }
                if (orderSelectItemVo.getWeight().intValue() != 0) {
                    orderSelectItemVo.setCurrentPrice(orderSelectItemVo.getProductTotalPrice().divide(orderSelectItemVo.getWeight(), 2));
                }
                newItems.add(orderSelectItemVo);
            }


//        order.setOrderSelectItemVos(orderSelectItemVoList);
//            JSON.toJSONString(newItems, SerializerFeature.DisableCircularReferenceDetect);
            order.setOrderSelectItemVos(newItems);

            String paymentVoucherImg = mallPaymentVoucherMapper.selectPaymentVoucher(order.getOderNo());
            order.setPaymentVoucherImg(paymentVoucherImg);
            //订单流程已弃用合同板块
//            Long endTime;
//            if(order.getSalesContNo() != null && !"".equals(order.getSalesContNo())){
//                if(order.getStatus()==30){
//                    endTime= (Long) contService.salesContAgreeYesEndOrderTime(userId,order.getSalesContNo()).getData();
//                    order.setEndTime(endTime);
////                }else if(order.getStatus()==36){
////                    endTime= (Long) contService.salesContAgreeYesEndOrderTime(userId,order.getSalesContNo()).getData();
////                    order.setEndTime(endTime);
////                }
//            }
            //如果是现金用户并且没上传过凭证返回0，如果上传过返回1
            //账期用户为-1
            Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(userId);
            SysCustomerCredit sysCustomerCredit = sysCustomerCreditMapper.selectByCustomerId(customerId);
            if(null == sysCustomerCredit) {
                order.setPaymentVoucherStatus(-1);
            }else{
                Integer count  = mallPaymentVoucherMapper.selectCountByOrderNo(orderNo);
                if(0 == count) order.setPaymentVoucherStatus(0);
                else order.setPaymentVoucherStatus(1);
            }

            list.add(order);
        }

       if (list==null||list.size()==0){
           return ServerResponse.createByStatus(ResponseCode.ORDER_SELECT_NOT_ERROR.getCode(),ResponseCode.ORDER_SELECT_NOT_ERROR.getDesc(),new PageVo(pageNo,pageSize,0,list));
       }
       PageVo pageVo = new PageVo(pageNo, pageSize, totalRecord,list);
        return ServerResponse.createBySuccess("订单查询成功",pageVo) ;
    }

    //查询所有已选择订单产品
    public ServerResponse<List<OrderSelectVo>> getOrderCartProduct(
                                        Integer userId,MallShipping shipping,Integer paymentType,MallDistmode distmode,
                                        String message,String invoiceRecPerson,String invoiceRecPhone,String invoiceRecAddress
          ){

        //查询出商家id数组

        //现在不拆单

        List<ShopVo> shops= cartMapper.selectShopIdsByUserId(userId);
        if (null==shops||shops.size()==0){
            return  ServerResponse.createByStatus(ResponseCode.SHOP_NOT_FOUND.getCode(),ResponseCode.SHOP_NOT_FOUND.getDesc(),null);
        }
        //创建订单集合
        List<OrderSelectVo> orderItemList = Lists.newArrayList();
        //通过用户选择的购物车产品
        for(ShopVo shop:shops){
            List<MallCart> mallCarts=  cartMapper.selectCheckedCartByByShopId(userId,shop.getShopId());
            //创建订单
            OrderSelectVo orderSelectVo= getCartByShop(shop,userId,mallCarts,shipping,paymentType,distmode,message, invoiceRecPerson, invoiceRecPhone, invoiceRecAddress).getData();
            orderItemList.add(orderSelectVo);
        }
        //生成订单 订单明细
//        createCartOrder(userId,orderItemList);
        //获取产品选中列表 有 单价 数量 总价 名称 URL img
        return ServerResponse.createBySuccess(orderItemList);
    }

    // 通过商家 每个商家创建订单收集订单数据
    private ServerResponse<OrderSelectVo> getCartByShop(ShopVo shopVo,Integer userId, List<MallCart> cartList,MallShipping shipping,Integer paymentType,MallDistmode distmode,
                                                String message,String invoiceRecPerson,String invoiceRecPhone,String invoiceRecAddress){
        Date date= new Date();//创建时间
       //生成订单号
        Integer dealerId = sysDeptCustomerMapper.selectDealerIdByUserId(userId);
        Long orderNo = NumberUtil.createOrderNo(dealerId);
//        Long orderNo=OrderUtils.generateOrderNo();
        //创建订单
        OrderSelectVo order= new OrderSelectVo();
        order.setCreateTime(date);
        order.setOderNo(orderNo);
        order.setShopId(shopVo.getShopId());
        order.setShopName(shopVo.getShopName());
        order.setPaymentType(paymentType);
        order.setShippingId(shipping.getId());
        order.setUserId(userId);
        order.setIsSample(0);
        //审核中
        order.setStatus(ResponseCode.ORDER_EXAMINE.getCode());
        order.setDistCode(distmode.getDistCode());
        order.setEnabled(1);
        order.setMessage(message);
        order.setInvoiceRecPerson(invoiceRecPerson);
        order.setInvoiceRecAddress(invoiceRecAddress);
        order.setInvoiceRecPhone(invoiceRecPhone);




        List<OrderSelectItemVo> orderItemList = Lists.newArrayList();
        BigDecimal payment= new BigDecimal(0.0);
       //List<CartProductTempVo> orderProTempList = Lists.newArrayList();
        if(CollectionUtils.isEmpty(cartList)){
            return ServerResponse.createByErrorMessage("购物车为空");
        }

        //校验购物车的数据,包括产品的状态和数量
        for(MallCart cart: cartList){
            int productId=cart.getProductId();
            MallProduct product =null;
            try{
                product=  productMapper.selectByProductId(productId);
            }catch (Exception e){
                e.printStackTrace();
                return ServerResponse.createByStatus(300,"产品查询错误",null);
            }

            if(null==product){
                return ServerResponse.createByErrorMessage("产品不存在");
            }
            if(Const.ProductStatusEnum.ON_SALE.getCode() != product.getStatus()){
                return ServerResponse.createByErrorMessage("产品"+product.getName()+"不是在线售卖状态");
            }
            //通过重量 id 等级查询出产品数量
            BigDecimal weight=cart.getWeight();
            if(weight.intValue() == 0){
                return ServerResponse.createByErrorCodeMessage(ResponseCode.CART_WEIGHT_ISEMPTY.getCode(), ResponseCode.CART_WEIGHT_ISEMPTY.getDesc());
            }
            String grade=cart.getGrade();
            int checked=cart.getChecked();
            BigDecimal price= new BigDecimal(0.0);
            MallPrice mallPrice=null;
            OrderSelectItemVo orderItemVo=new OrderSelectItemVo();
            //CartProductTempVo cartProductTempVo= new CartProductTempVo();
            //获取数量
            if(null!=grade&&!"".equals(grade)){
                try {
                    mallPrice = priceMapper.selectPriceNum(productId,weight,grade);
                }
                 catch (Exception e) {
                    e.printStackTrace();
                    return ServerResponse.createByStatus(300,"产品查询错误",null);
                }
                if(mallPrice==null){
                    return ServerResponse.createByStatus(303,"产品找不到对应的价格",null);
                }
                orderItemVo.setGrade(grade);
            }

            //将来将去除区间价
            price = price.add(mallPrice.getPriceNum());

            //创建临时产品
            orderItemVo.setProductMainImage(product.getMainImage());
            orderItemVo.setProductId(product.getId());
            orderItemVo.setProducName(product.getName());
            orderItemVo.setIsChecked(checked);
            orderItemVo.setCurrentPrice(price);
            orderItemVo.setWeight(weight);
            orderItemVo.setCreateTime(date);
            orderItemVo.setProductTotalPrice(weight.multiply(price));

            orderItemList.add(orderItemVo);
            payment = payment.add(weight.multiply(price));//订单总金额
            payment = new BigDecimal(DecimalFormatUtrils.dataFomateTwo(payment.doubleValue()));//小数两位
        }
        order.setPayment(payment);
        order.setOrderSelectItemVos(orderItemList);

        return ServerResponse.createBySuccess(order);
    }
    public ServerResponse<OrderVo> getOrderDetail(Integer userId, Long orderNo){
        MallOrder order = orderMapper.selectByUserIdAndOrderNo(userId,orderNo);
        if(order != null){
            List<MallOrderItem> orderItemList = orderItemMapper.getByOrderNoUserId(orderNo,userId);
            OrderVo orderVo = assembleOrderVo(order,orderItemList);
            return ServerResponse.createBySuccess(orderVo);
        }
        return  ServerResponse.createByErrorMessage("没有找到该订单");
    }
    //订单详情

    //后期维护
    public ServerResponse<OrderSelectVo> selectOrderByOrderNo(Integer userId,Long orderNo){
        OrderSelectVo orderSelectVo= new OrderSelectVo();
       //查询发票
      //  UnitContactVo invoice =null;
//        try {
//            invoice=  sysUserDetailMapper.selectUnitByUserId(userId);
//            OrderSelectVo order = null;
//        }catch (Exception e) {
//            e.printStackTrace();
//            return ServerResponse.createByStatus(ResponseCode.INVOICE_NOT_FOUND.getCode(),ResponseCode.INVOICE_NOT_FOUND.getDesc(),orderSelectVo) ;
//        }
//        if(invoice==null){
//            return ServerResponse.createByStatus(ResponseCode.INVOICE_NOT_FOUND.getCode(),ResponseCode.INVOICE_NOT_FOUND.getDesc(),orderSelectVo) ;
//        }
        OrderSelectVo order=null;
        try {
            order=orderMapper.selectOrderByOrderNo(orderNo);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByStatus(ResponseCode.ORDER_SELECT_ERROR.getCode(),ResponseCode.ORDER_SELECT_ERROR.getDesc(),orderSelectVo) ;
        }
        if (null==order){
            return ServerResponse.createByStatus(ResponseCode.ORDER_SELECT_NULL.getCode(),ResponseCode.ORDER_SELECT_NULL.getDesc(),orderSelectVo) ;
        }
        //看不到
        List<OrderSelectItemVo> orderSelectItemVoList = order.getOrderSelectItemVos();
//        if(orderSelectItemVoList != null) {
//            for (OrderSelectItemVo orderSelectItemVo : orderSelectItemVoList) {
//                if (orderSelectItemVo.getGrade() == null) {
//                    continue;
//                }
//                String grade = orderSelectItemVo.getGrade();
//                if (grade == null || "".equals(grade)) {
//                    continue;
//                }
//                if (grade.contains("定重")) {
//                    if (grade.contains("不")) {
//                        grade = "AA不定重";
//                    } else {
//                        grade = "AA定重";
//                    }
//                }
//                orderSelectItemVo.setGrade(grade);
//            }
//        }

        if(orderSelectItemVoList != null) {
            //2019/1/11 相同等级的要进行分组
            Multimap multimap = HashMultimap.create();
            for(OrderSelectItemVo itemVos:orderSelectItemVoList){
                String grade = itemVos.getGrade();
                if(grade.contains("AA") && grade.contains("定重") && !grade.contains("不")){
                    multimap.put("AA定重-" + itemVos.getProductId(), itemVos);
                }else if(grade.contains("AA") && grade.contains("不定重")){
                    multimap.put("AA不定重-" + itemVos.getProductId(), itemVos);
                }else{
                    multimap.put(grade + "-" + itemVos.getProductId(), itemVos);
                }
            }
            List<OrderSelectItemVo> newItems = new ArrayList<>();
            for(Object obj: multimap.keys()){
                Set<OrderSelectItemVo> set = ((HashMultimap) multimap).get(obj);
                OrderSelectItemVo orderSelectItemVo = new OrderSelectItemVo();

                Iterator iter = set.iterator();

                int count = 0;
                while(iter.hasNext()) {
                    OrderSelectItemVo subOrderSelectItemVo = (OrderSelectItemVo) iter.next();

                    if(count == 0){
                        count = 1;
//                        orderSelectItemVo = subOrderSelectItemVo;
                        BeanUtils.copyProperties(subOrderSelectItemVo, orderSelectItemVo);
                        continue;
                    }
                    String str = (String)obj;
                    orderSelectItemVo.setGrade(((String) obj).split("-")[0]);
                    BigDecimal weight = orderSelectItemVo.getWeight() == null ? new BigDecimal(0) : orderSelectItemVo.getWeight();
                    BigDecimal productTotalPrice = orderSelectItemVo.getProductTotalPrice() == null ? new BigDecimal(0.0) : orderSelectItemVo.getProductTotalPrice();
                    orderSelectItemVo.setWeight(weight.add(subOrderSelectItemVo.getWeight()));
                    orderSelectItemVo.setProductTotalPrice(productTotalPrice.add(subOrderSelectItemVo.getProductTotalPrice()));
                }
                if (orderSelectItemVo.getWeight().intValue() != 0) {
                    orderSelectItemVo.setCurrentPrice(orderSelectItemVo.getProductTotalPrice().divide(orderSelectItemVo.getWeight(), 2));
                }
                newItems.add(orderSelectItemVo);
            }


//        order.setOrderSelectItemVos(orderSelectItemVoList);
            order.setOrderSelectItemVos(newItems);
        }

        MallOrder mallOrder = mallOrderMapper.selectAllOrderNo(orderNo);


        List<MallOrderRemark> mallOrderRemarkList = mallOrderRemarkMapper.selectByOrderNoWithType(orderNo, 1);
        List<OrderRemarkVo> orderRemarkVoList = new ArrayList<>();

        for(MallOrderRemark mallOrderRemark : mallOrderRemarkList){
            OrderRemarkVo tOrderRemarkVo = new OrderRemarkVo();
            tOrderRemarkVo.setCreateTime(mallOrderRemark.getCreateTime());
            tOrderRemarkVo.setType(1);
            tOrderRemarkVo.setUserId(mallOrderRemark.getUserId());
            tOrderRemarkVo.setUserName(userMapper.selectByPrimaryKey(mallOrderRemark.getUserId()).getRealName());
            tOrderRemarkVo.setOrderNo(mallOrderRemark.getOrderNo());
            tOrderRemarkVo.setOpinion(mallOrderRemark.getContent());

            orderRemarkVoList.add(tOrderRemarkVo);
        }

        OrderRemarkVo orderRemarkVo = new OrderRemarkVo();
        orderRemarkVo.setCreateTime(mallOrder.getCreateTime());
        orderRemarkVo.setType(0);
        orderRemarkVo.setOpinion(mallOrder.getMessage());
        orderRemarkVo.setOrderNo(orderNo);


        //创建订单入口1.用户 2.业务员
        if(mallOrder.getSubmitPerson() == 1) {
            orderRemarkVo.setUserId(mallOrder.getUserId());
            orderRemarkVo.setUserName(userMapper.selectByPrimaryKey(mallOrder.getUserId()).getRealName());
        }
        else {
            Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(mallOrder.getUserId());
            Integer salesmanId = sysCustomerMapper.selectByPrimaryKey(customerId).getSalesmanId();
            String userName = userMapper.selectByPrimaryKey(salesmanId).getRealName();
            orderRemarkVo.setUserId(salesmanId);
            orderRemarkVo.setUserName(userName);
        }


        //审核备注 可以多条
        orderRemarkVoList.add(orderRemarkVo);

        order.setOrderRemarkVoList(orderRemarkVoList);





//        if(userId != order.getUserId()){
//            return ServerResponse.createByErrorMessage("该用户无该订单");
//        }
//        order.setTaxNum(invoice.getTaxNum());
//        order.setInvoiceTitle(invoice.getInvoiceTitle());
//        order.setInvoiceTitleAddr(invoice.getInvoiceTitleAddr());
//        order.setBusAddress(invoice.getAddress());
//        order.setBusTel(invoice.getTel());
//        order.setBankName(invoice.getBankName());
//        order.setBankAccount(invoice.getBankAccount());;
        if(order.getOpinion()==null){
            order.setOpinion("暂无审核结果");
        }
//        //如果有合同 就返回倒计时
//        MallOrderSalesContVo  contVo=orderSalesContMapper.selectSalesContByOderNo(orderNo);
//        if (null!=contVo&&null!=contVo.getCreateTime()) {
//            Long endTime;
//            if(order.getStatus()==30){
//                try {
//                    //如果是审核通过返回倒计时
//                    Calendar calendar = Calendar.getInstance();
//                    calendar.setTime(new Date());
//                    long nowTime = calendar.getTimeInMillis();
//                    calendar.setTime(contVo.getUpdateTime());
//                    long before = calendar.getTimeInMillis();
//                    endTime = nowTime - before;
////                    endTime=(Long) contService.salesContAgreeYesEndOrderTime(userId,order.getSalesContNo()).getData();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    return ServerResponse.createByStatus(ResponseCode.ORDERSALE_CONT_SELECT_NULL.getCode(),ResponseCode.ORDERSALE_CONT_SELECT_NULL.getDesc(),orderSelectVo) ;
//                }
//                order.setEndTime(endTime);
//            }else if(order.getStatus()==36){
//                try {
//                    endTime=(Long) contService.salesContAgreeNoEndOrderTime(userId,order.getSalesContNo()).getData();
//                    order.setEndTime(endTime);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    return ServerResponse.createByStatus(ResponseCode.ORDERSALE_CONT_SELECT_NULL.getCode(),ResponseCode.ORDERSALE_CONT_SELECT_NULL.getDesc(),orderSelectVo) ;
//                }
//            }
//        }
        //添加发货列表
        List<OrderSendVo> orderSendVoList = new ArrayList<>();

        List<MallOrderFufillmentParent> mallOrderFufillmentParentList = mallOrderFufillmentParentMapper.selectByOrderNo(orderNo);
        if(mallOrderFufillmentParentList.size() != 0) {
            for (MallOrderFufillmentParent mallOrderFufillmentParent : mallOrderFufillmentParentList) {
                OrderSendVo orderSendVo = new OrderSendVo();

                String fufillmentNo = mallOrderFufillmentParent.getFufillmentNo();
                List<ProductFufillmentVo> productFufillmentVoList = new ArrayList<>();
                List<MallOrderFufillment> mallOrderFufillmentList = mallOrderFufillmentMapper.selectByFufillmentNo(fufillmentNo);
                for (MallOrderFufillment mallOrderFufillment : mallOrderFufillmentList) {
                    ProductFufillmentVo productFufillmentVo = new ProductFufillmentVo();
                    productFufillmentVo.setModel(mallOrderFufillment.getModel());
                    MallOrderItem mallOrderItem = mallOrderItemMapper.selectByPrimaryKey(mallOrderFufillment.getOrderItemId());
                    if(mallOrderItem == null) {
                        continue;
                    }
                    Integer productId = mallOrderItem.getProductId();
                    productFufillmentVo.setProductId(productId);
                    productFufillmentVo.setWeight(mallOrderFufillment.getWeight());
                    productFufillmentVo.setName(mallOrderItem.getProductName());
                    productFufillmentVo.setImg(mallOrderItem.getProductImage().split(",")[0]);
                    productFufillmentVo.setGrade(mallOrderItem.getGrade());

                    productFufillmentVoList.add(productFufillmentVo);
                }
                orderSendVo.setProductFufillmentVoList(productFufillmentVoList);
                orderSendVo.setIsReceive(mallOrderFufillmentParent.getIsReceived());
                orderSendVo.setRemark(mallOrderFufillmentParent.getRemark());
                orderSendVo.setOrderFufillmentNo(mallOrderFufillmentParent.getFufillmentNo());
                orderSendVo.setSendTime(mallOrderFufillmentParent.getCreateTime());
                orderSendVo.setAddress(mallOrderFufillmentParent.getAddress());

                orderSendVoList.add(orderSendVo);
            }
        }

        //发货清单
        order.setOrderSendVoList(orderSendVoList);

        List<OrderSelectItemVo> itemList=null;
        try {
            itemList= orderMapper.selectOrderItemsByOrderNo(orderNo);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByStatus(ResponseCode.ORDER_ITEM_SELECT_ERROR.getCode(),ResponseCode.ORDER_ITEM_SELECT_ERROR.getDesc(),orderSelectVo) ;
        }
        if(null==itemList||itemList.size()==0){
            return ServerResponse.createByStatus(ResponseCode.ORDER_ITEM_SELECT_NOT_NULL.getCode(),ResponseCode.ORDER_ITEM_SELECT_NOT_NULL.getDesc(),orderSelectVo) ;
        }
        //查询评论
        int commentCheck=orderMapper.selectComment(order.getOderNo());
        order.setCommentCheck(commentCheck);
        order.setOrderSelectItemVos(itemList);

        //PC端需要非空的发货时间
        if(order.getSendDate() == null){
            order.setSendDate("");
        }

        order.setMallTransport(mallTransportMapper.selectByPrimaryKey(order.getTransportId()));

        return  ServerResponse.createByStatus(ResponseCode.SUCCESS.getCode(),ResponseCode.SUCCESS.getDesc(),order);
    }

    public ServerResponse<PageInfo> getOrderList(Integer userId, int pageNum, int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<MallOrder> orderList = orderMapper.selectByUserId(userId);
        List<OrderVo> orderVoList = assembleOrderVoList(orderList,userId);
        PageInfo pageResult = new PageInfo(orderList);
        pageResult.setList(orderVoList);
        return ServerResponse.createBySuccess(pageResult);
    }



    private List<OrderVo> assembleOrderVoList(List<MallOrder> orderList, Integer userId){
        List<OrderVo> orderVoList = Lists.newArrayList();
        for(MallOrder order : orderList){
            List<MallOrderItem>  orderItemList = Lists.newArrayList();
            if(userId == null){
                //todo 管理员查询的时候 不需要传userId
                orderItemList = orderItemMapper.getByOrderNo(order.getOrderNo());
            }else{
                orderItemList = orderItemMapper.getByOrderNoUserId(order.getOrderNo(),userId);
            }
            OrderVo orderVo = assembleOrderVo(order,orderItemList);
            orderVoList.add(orderVo);
        }
        return orderVoList;
    }




    public ServerResponse queryOrderPayStatus(Integer userId, Long orderNo){
        MallOrder order = orderMapper.selectByUserIdAndOrderNo(userId,orderNo);
        if(order == null){
            return ServerResponse.createByErrorMessage("用户没有该订单");
        }
        if(order.getStatus() >= Const.OrderStatusEnum.PAID.getCode()){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }


    //创建订单 快捷购买
    //0：快捷购买 1：拿样
    //String message,String invoice_rec_person,String invoice_rec_phone,String invoice_rec_address
    public ServerResponse<OrderSelectVo> createOrderSimpleOrQuick2(String agent, Integer isSample,Integer userId, Integer shippingId,  Integer productId, BigDecimal weight, String grade,Integer distId,
         String message,String invoiceRecPerson,String invoiceRecPhone,String invoiceRecAddress,Integer dealerId, Integer transportId) {

        //生产订单号
         dealerId = sysDeptCustomerMapper.selectDealerIdByUserId(userId);
        Long orderNo = NumberUtil.createOrderNo(dealerId);
//        long orderNo = OrderUtils.generateOrderNo();

        //
        Integer status;//状态
        //运费
        Integer postage=0;
        BigDecimal price=null;
        //通过产品id查询产品对象
        Map<String,Object> productMap=null;
        try {
            productMap=productMapper.selectByProductIdQuk(productId);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByStatus(ResponseCode.PRODUCT_NOT_FOUND.getCode(),ResponseCode.PRODUCT_NOT_FOUND.getDesc(),null);
        }
        if (null==productMap){
            return ServerResponse.createByStatus(ResponseCode.PRODUCT_NOT_FOUND.getCode(),ResponseCode.PRODUCT_NOT_FOUND.getDesc(),null);
        }
        BigDecimal priceTotal = new BigDecimal(0.0);
        //设置配送方式
        MallDistmode distmode=null;
        OrderSelectVo order=new OrderSelectVo();
        Integer shopId= (Integer) productMap.get("shop_id");
        order.setShopId(shopId);
        MallPrice mallPrice;
        //如果拿样 价格==0
        if (isSample==1){
            order.setIsSample(1);
            order.setDistCode(2);//华鼎配送


            //2018/10/30 一个月拿样不能超过五次
            Calendar calendar = Calendar.getInstance();
            Integer year = calendar.get(Calendar.YEAR);
            Integer month = calendar.get(Calendar.MONTH);
            calendar.set(year, month, 1, 0, 0, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            Date start = calendar.getTime();
            calendar.set(Calendar.MONTH, month + 1);
            Date end = calendar.getTime();
            Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(userId);
            Integer sampleCount = orderMapper.selectSampleWithCustomerId(customerId, start, end);
            if (sampleCount>=2){
                return ServerResponse.createByErrorMessage("拿样一个月不能超过2次");
            }


            postage=0;
            //如果超过1000不能那样
            if(weight.doubleValue() > 5){
                return ServerResponse.createByErrorMessage("单次拿样不能超过5kg");
            }
            //如果取样未付款状态
            //已付款
            status=ResponseCode.ORDER_PAID.getCode();
            price=new BigDecimal(0);
            priceTotal = new BigDecimal(0.0);
            /*try {
                //确定那样价格
                price=  priceMapper.selectPriceNumSample(productId,grade);
            } catch (Exception e) {
                e.printStackTrace();
                return ServerResponse.createByStatus(22,"找不到该商品价格","");
            }*/
            //————————————————————————
            //拿样消息推送给后台
            backPush(userId, orderNo, 1);

        }else{
            order.setIsSample(0);
            postage=20;
            //审核中
            status=ResponseCode.ORDER_EXAMINE.getCode();;
            try {
                mallPrice=priceMapper.selectPriceNum(productId,weight,grade);
            } catch (Exception e) {
                e.printStackTrace();
                return ServerResponse.createByStatus(ResponseCode.PRODUCT_PRICE_NOT_FOUND.getCode(),ResponseCode.PRODUCT_PRICE_NOT_FOUND.getDesc(),null);
            }
            if(null==mallPrice){
                price=new BigDecimal(0.0);
            }else {
                price = mallPrice.getPriceNum();
            }
            priceTotal=price.multiply(weight);
            try {
                distmode=distmodeMapper.selectById(distId);
            } catch (Exception e) {
                e.printStackTrace();
                return  ServerResponse.createByStatus(51,"配送方式查询无效",null);
            }
            if(null==distmode){
                return  ServerResponse.createByStatus(51,"配送方式查询无效",null);
            }
            order.setDistCode(distmode.getDistCode());

            //————————————————
            //普通订单推送给后台
            backPush(userId, orderNo, 2);
        }

        String model=null;
        try {
            model=productMapper.selectModelByProductId(productId);
        } catch (Exception e) {
            e.printStackTrace();
            return  ServerResponse.createByStatus(ResponseCode.PRODUCT_NOT_FOUND.getCode(),ResponseCode.PRODUCT_NOT_FOUND.getDesc(),null);
        }

        //生成订单明细
        String productName= (String) productMap.get("productName");
        String productMainImage= (String) productMap.get("productMainImage");
        Integer commentCheck=0;//未评论
        try{
            int orderItemInst=orderItemMapper.insertQuk(orderNo,userId,productId,productName,productMainImage,price,weight,priceTotal,grade,commentCheck,model);
        }catch (Exception e){
            e.printStackTrace();
            return  ServerResponse.createByStatus(41,"订单明细插入有误",null);
        }


        order.setMessage(message);
        order.setInvoiceRecPerson(invoiceRecPerson);
        order.setInvoiceRecPhone(invoiceRecPhone);
        order.setInvoiceRecAddress(invoiceRecAddress);
        order.setOderNo(orderNo);
        order.setShippingId(shippingId);
        order.setUserId(userId);
        order.setPayment(priceTotal);
        //DecimalFormat df=new DecimalFormat("#.00");
        order.setPaymentType(1);
        order.setStatus(status);
        //运费
        order.setPostage(postage);
        order.setEnabled(1);

        order.setMessage(message);

        order.setTransportId(transportId);
        //生成订单
        try {

            int orderInsert = orderMapper.insertOrderCart(orderNo,order,dealerId);
        }catch (Exception e){
            e.printStackTrace();
            return  ServerResponse.createByStatus(300,"订单生成有误",null);
        }
        //2018/12/21要记录购买方式和购买的设备信息
        try {
            mallOrderMapper.updateCreateReason(agent, orderNo, "快速购买");
        }catch (Exception e){
            //记录失败
            log.info("记录购买方式和购买的设备信息失败");
        }
        return  ServerResponse.createByStatus(0,"订单生成成功",order);

    }

    //创建订单
    //0：快捷购买 1：拿样
   /* public ServerResponse<BlankVo> createOrderSimpleOrQuick(Integer userId, Integer shippingId, Integer orderType, Integer productId, Integer weight, String grade) {

        //获得订单详情
        MyOrderVo myOrderVo = (MyOrderVo) getOrderSimpleOrQuick(userId, orderType, productId, weight, grade).getData();


        MallProduct product = myOrderVo.getProduct();
        product.setStock(product.getStock() - myOrderVo.weight);
        productMapper.updateByPrimaryKeySelective(product);

        //创建订单
        MallOrder order = this.assembleOrder(userId, shippingId, myOrderVo.getPrice());

        if(order == null){
            return ServerResponse.createByErrorMessage("生成订单错误");
        }


        return ServerResponse.createBySuccess(new BlankVo(order.getOrderNo(), myOrderVo.getPrice()));


    }*/

    //获得产品列表
    //0：快捷购买 1：拿样
    /*public ServerResponse getOrderSimpleOrQuick(Integer userId, Integer orderType, Integer productId, Integer weight, String grade) {

        MallProduct product = productMapper.selectByProductId(productId);
        BigDecimal price = new BigDecimal("0");
        MallPrice mallPrice;
        Double samplePrice = 0.0;
        //列出价格
        if(orderType == 1) {
            samplePrice = product.getPrice().doubleValue();
            price = BigDecimalUtil.mul(weight >= 5 ? weight : 0, samplePrice);
        } else if(orderType == 0){
            //快捷购买为浮动的价格
            //需要去产品表里面查询
            mallPrice = priceMapper.selectPriceNum(productId, weight, grade).doubleValue();
            price = BigDecimalUtil.mul(weight, samplePrice);
        }

        //需要校验库存
        int stock = product.getStock();
        if(weight > stock){
            return ServerResponse.createByErrorMessage("库存不足");
        }


        MyOrderVo orderVo = new MyOrderVo();
        orderVo.setProduct(product);
        orderVo.setOrderType(orderType);
        orderVo.setPrice(price);
        orderVo.setWeight(weight);

        return ServerResponse.createBySuccess(orderVo);
    }
*/
    //根据获得的地址匹配数据库中 以,隔开
    public ServerResponse<List<MallFreightVo>> getFreight(Integer shippingId) {


        MallShipping mallShipping = shippingMapper.selectByShippingId(shippingId);

        //先筛选一遍省市区
        String province = mallShipping.getReceiverProvince();
        province = province.endsWith("省") ? province.substring(0, province.length() - 1) : province;

        String city = mallShipping.getReceiverCity();
        city = city.endsWith("市") ? city.substring(0, city.length() - 1) : city;

        String district = mallShipping.getReceiverDistrict();
        district = district.endsWith("区") ? district.substring(0, district.length() - 1) : district;

        List<MallFreight> mallFreightList = mallFreightMapper.findAddr(province, city, district);

        //再查看详细地址中是否有匹配的地址
        List<MallFreight> allMallFreightList = mallFreightMapper.selectAll();
        String addr = mallShipping.getReceiverAddress();
        for(MallFreight mallFreight : allMallFreightList){
            if(addr.contains(mallFreight.getArea())){
                mallFreightList.add(mallFreight);
            }
        }

        List<MallFreightVo> mallFreightVoList = new ArrayList<MallFreightVo>();
        for(int i = 0; i < mallFreightList.size(); i++) {
            BigDecimal startPrice = mallFreightList.get(i).getStartPrice();
            BigDecimal endPrice = mallFreightList.get(i).getEndPrice();
            String price = "";
            if(startPrice.equals(endPrice)){
                price = startPrice.toString();
            } else{
                price = startPrice.toString() + "-" + endPrice;
            }
            MallFreightVo mallFreightVo = new MallFreightVo(mallFreightList.get(i).getArea(), price);
            mallFreightVoList.add(mallFreightVo);
        }


        //如果所选地址下没有华鼎配送的地址，匹配通用
        //规则：
        //义乌本地 100-200 江浙沪 250-600 闽三角 400-600 珠三角 500-800 其他地区 800-1200

        if(mallFreightList.size() == 0){
            return ServerResponse.createByStatus(52, "请联系客服，该收货地址暂无配送价格");
        }

        return ServerResponse.createBySuccess(mallFreightVoList);
    }

    /*public ServerResponse deleteOrder(Integer userId) {

        try{
            orderMapper.deleteByUserId(userId);
            orderItemMapper.deleteByUserId(userId);
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByStatus(42 ,"订单删除失败");
        }
        return ServerResponse.createBySuccess("订单删除成功");
    }*/
    public ServerResponse deleteOrderByOrderNo(Long orderNo) {

        try{
            orderMapper.deleteOrderByOrderNo(orderNo);
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByStatus(42 ,"订单删除失败");
        }
        return ServerResponse.createBySuccess("订单删除成功");
    }

    public ServerResponse changeOrderStatus(Integer orderId, Integer status) {

        try {
            orderMapper.changeOrderStatus(orderId, status);
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("订单状态改变失败");
        }
        return ServerResponse.createBySuccess("订单状态改变成功");
    }

    public ServerResponse findOrderStatus(Integer userId) {

       Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        List<MallOrder> mallOrderList = new ArrayList<MallOrder>();
        try {
            mallOrderList = orderMapper.findOrderStatus(userId);
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("查找订单失败");
        }

        for(MallOrder mallOrder : mallOrderList){
            map.put(mallOrder.getId(), mallOrder.getStatus());
        }
        return ServerResponse.createBySuccess(map);


    }

    public void changeOrderStatusByOrderNum(Long orderNo, int status) {

            orderMapper.updateByOrderNo(status, orderNo);
    }

    public ServerResponse<List<OrderSelectVo>> cartCreate(String agent, Integer userId, Integer shippingId, Integer distId, Integer paymentType,
                                                          String message, String invoiceRecPerson, String invoiceRecPhone, String invoiceRecAddress, Integer transportId) {

       // Integer dealerId =  userMapper.selectByUserIdToDealerId(userId);
        //查看用户绑定的办事处
        Integer dealerId = sysCustomerMapper.selectByUserId(userId).getDealerId();


        //增加验证是否有商家绑定信息
        SysDeptVo buyerDept =  sysUserDeptMapper.selectDeptByUserId(userId);
        if(buyerDept==null){
            return ServerResponse.createByStatus(ResponseCode.DEPT_SELECT_ISNULL_ERROR.getCode(),ResponseCode.DEPT_SELECT_ISNULL_ERROR.getDesc());
        }
        //如果是空 报没有这个用户对象---

        //查地址对象
         MallShipping shipping = shippingMapper.selectByPrimaryKey(shippingId);
        if(null == shipping){
            return  ServerResponse.createByStatus(301,"没有这个送货地址",null);
        }

        MallDistmode distmode= distmodeMapper.selectById(distId);
        if(null == distmode){
            return  ServerResponse.createByStatus(301,"没有这个配送方式",null);
        }
        //获取订单中勾选商品
       ServerResponse<List<OrderSelectVo>> response = getOrderCartProduct(userId,shipping,paymentType,distmode,message,invoiceRecPerson,invoiceRecPhone,invoiceRecAddress);

        List<OrderSelectVo> orderList = response.getData();
        if(null==orderList){
            return ServerResponse.createByStatus(ResponseCode.ORDER_SELECT_NULL.getCode(),ResponseCode.ORDER_SELECT_NULL.getDesc(),null);
        }
        //创建订单
        createCartOrder(userId, agent, orderList, dealerId, message, transportId);

//        SysUserRole userRole =userRoleMapper.selectRole(userId);
//        if(null == userRole)
//        return ServerResponse.createByErrorMessage("查询角色错误");

        //Bi
//        BiActionHisParamsVo biActionHisParamsVo=new BiActionHisParamsVo();
//        biActionHisParamsVo.setRequest(request);
//        biActionHisParamsVo.setAction("购物车创建订单");
//        biActionHisParamsVo.setActionUrl("order/cartCreate");
//        biActionHisParamsVo.setUserRoleId(userId);
//    //    biActionHisParamsVo.setUserRoleName(userRole.getRoleName());
//        biActionHisParamsVo.setContent(JsonUtils.arrayToJsonStr(orderList));
//        biActionHisParamsVo.setUser(userMapper.selectByPrimaryKey(userId));
//        BiUserActionHistoryService biUserActionHistoryService = new BiUserActionHistoryService();
//        biUserActionHistoryService.insertActionHis(biActionHisParamsVo);
        return response;

    }

    public ServerResponse<OrderFufillmentParentVo> getOrderFufillmentListorderNo(Integer userId, Long orderNo) {

        MallOrder mallOrder = mallOrderMapper.selectByOrderNo(orderNo);
//        if(null != mallOrder && mallOrder.getUserId() != userId){
//            return ServerResponse.createByErrorMessage("该用户无该订单");
//        }

        List<MallOrderFufillmentParent> mallOrderFufillmentParentList = mallOrderFufillmentParentMapper.selectByOrderNo(orderNo);
        OrderFufillmentParentVo orderFufillmentParentVo = new OrderFufillmentParentVo();

        //发货信息
        List<OrderFufillmentVo> orderFufillmentVoList = new ArrayList<OrderFufillmentVo>();
        if(mallOrderFufillmentParentList.size() != 0) {
            for (MallOrderFufillmentParent mallOrderFufillmentParent : mallOrderFufillmentParentList) {
                OrderFufillmentVo orderFufillmentVo = new OrderFufillmentVo();
                String fufillmentNo = mallOrderFufillmentParent.getFufillmentNo();
                List<MallOrderFufillment> mallOrderFufillmentList = mallOrderFufillmentMapper.selectByFufillmentNo(fufillmentNo);
                List<ProductFufillmentVo> productFufillmentVoList = new ArrayList<>();
                for (MallOrderFufillment mallOrderFufillment : mallOrderFufillmentList) {
                    MallOrderItem mallOrderItem = orderItemMapper.selectByPrimaryKey(mallOrderFufillment.getOrderItemId());
                    ProductFufillmentVo productFufillmentVo = new ProductFufillmentVo();
                    productFufillmentVo.setGrade(mallOrderItem.getGrade());
                    productFufillmentVo.setImg(mallOrderItem.getProductImage().split(",")[0]);
                    productFufillmentVo.setName(mallOrderItem.getProductName());
                    productFufillmentVo.setWeight(mallOrderFufillment.getWeight());
                    productFufillmentVo.setProductId(mallOrderItem.getProductId());
                    String model = mallOrderItem.getProductName().split(",")[2];
                    productFufillmentVo.setModel(model);
                    productFufillmentVoList.add(productFufillmentVo);
                }
                orderFufillmentVo.setIsReceive(mallOrderFufillmentParent.getIsReceived());
                orderFufillmentVo.setOrderFufillmentNo(fufillmentNo);
                orderFufillmentVo.setDistCode(mallOrderMapper.selectByOrderNo(mallOrderFufillmentParent.getOrderNo()).getDistcode());
                orderFufillmentVo.setAddress(mallOrderFufillmentParent.getAddress());
                orderFufillmentVo.setProductFufillmentVoList(productFufillmentVoList);
                orderFufillmentVo.setSendTime(mallOrderFufillmentParent.getCreateTime());
                String remark = mallOrderFufillmentParent.getRemark();
                orderFufillmentVo.setRemark(remark);
                orderFufillmentVo.setIsRemark(null == remark ? 0 : 1);

                orderFufillmentVoList.add(orderFufillmentVo);
            }
        }

        //余量
        //指的是这个订单的所有item
        List<RestOrderSendVo> restOrderSendVoList = new ArrayList<>();
        List<MallOrderItem> restMallOrderItemList = orderItemMapper.selectAllByOrderNo(orderNo);
        for(MallOrderItem mallOrderItem : restMallOrderItemList){
            RestOrderSendVo restOrderSendVo = new RestOrderSendVo();
            restOrderSendVo.setGrade(mallOrderItem.getGrade());
            restOrderSendVo.setOrderItemId(mallOrderItem.getId());
            restOrderSendVo.setImg(mallOrderItem.getProductImage().split(",")[0]);
            restOrderSendVo.setName(mallOrderItem.getProductName());
            restOrderSendVo.setProductId(mallOrderItem.getProductId());
            restOrderSendVo.setResidualQuantity(new BigDecimal(Math.max(mallOrderItem.getResidualQuantity().doubleValue(), 0)));
            restOrderSendVo.setModel(mallOrderItem.getProductName().split(",")[2]);
            restOrderSendVoList.add(restOrderSendVo);
        }

        orderFufillmentParentVo.setRestOrderSendVoList(restOrderSendVoList);
        orderFufillmentParentVo.setOrderNo(orderNo);
        orderFufillmentParentVo.setOrderFufillmentVoList(orderFufillmentVoList);

        return ServerResponse.createBySuccess(orderFufillmentParentVo);
    }


    public ServerResponse receiveToFufillment(Integer userId, String orderFufillmentNo, int isReceived) {

        //如果已经进行收货确认不能修改状态
        MallOrderFufillmentParent mallOrderFufillmentParent = mallOrderFufillmentParentMapper.selectByOrderFufillmentNo(orderFufillmentNo);
        if(mallOrderFufillmentParent == null) return ServerResponse.createByErrorMessage("请输入正确的发货单号");

//        if(mallOrderMapper.selectByOrderNo(mallOrderFufillmentParent.getOrderNo()).getUserId() != userId){
//            return ServerResponse.createByErrorMessage("该用户无该发货单号");
//        }
        if(mallOrderFufillmentParent.getIsReceived() == 1) {
            isReceived = -1;
        }
        // if(mallOrderFufillmentParent.getRemark())

        mallOrderFufillmentParentMapper.updateIFReceived(orderFufillmentNo, isReceived);

        //如果该发货单号的订单编号指定的发货列表全部已经接收，并且orderItem所有都为0
        Integer receiveCount = mallOrderFufillmentParentMapper.selectCountByOrderNoCheckRecieve(mallOrderFufillmentParent.getOrderNo(), 0);

        Integer itemCount = mallOrderItemMapper.selectResidualQuantity(mallOrderFufillmentParent.getOrderNo());

        if(0 == receiveCount && 0 == itemCount){
            orderMapper.updateByOrderNo(50, mallOrderFufillmentParent.getOrderNo());
        }


        return ServerResponse.createBySuccess();
    }

    public ServerResponse remarkToFufillment(Integer userId, String orderFufillmentNo, String remark) {

//        如果已经评论过，不能进行修改
        //如果已经进行收货确认不能修改状态
        MallOrderFufillmentParent mallOrderFufillmentParent = mallOrderFufillmentParentMapper.selectByOrderFufillmentNo(orderFufillmentNo);
        if(mallOrderFufillmentParent == null) return ServerResponse.createByErrorMessage("请输入正确的发货单号");
        if(mallOrderFufillmentParent.getRemark() != null) remark = null;
//        if(mallOrderMapper.selectByOrderNo(mallOrderFufillmentParent.getOrderNo()).getUserId() != userId){
//            return ServerResponse.createByErrorMessage("该用户无该发货单号");
//        }


        mallOrderFufillmentParentMapper.updateIFRemark(orderFufillmentNo, remark);
        return ServerResponse.createBySuccess();
    }

    public ServerResponse getDispositPay(Integer per, Long orderNo) {

        BigDecimal dispositPay = new BigDecimal(1.0);
        MallOrder mallOrder = orderMapper.selectByOrderNo(orderNo);
        dispositPay = dispositPay.multiply(new BigDecimal(0.01 * per));
        dispositPay = dispositPay.multiply(mallOrder.getPayment());
        return ServerResponse.createBySuccess(dispositPay);
    }

    //上传交易凭证之后
    //1.改变订单状态
    //2.保存
    public ServerResponse submitOrderPaymentVoucher(Integer userId, Long orderNo, BigDecimal dispositPay, String transactionNo, String voucherImg, Integer paymentType) {

        Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(userId);

        SysCustomerCredit sysCustomerCredit = sysCustomerCreditMapper.selectByCustomerId(customerId);
        //账期用户无法提交订单编号
        if(null != sysCustomerCredit && null != orderNo){
            return ServerResponse.createByErrorMessage("账期用户无法提交订单凭证");
        }

        if(null == voucherImg){
            return ServerResponse.createByErrorMessage("未上传支付凭证");
        }

        if(null == dispositPay){
            return ServerResponse.createByErrorMessage("未输入金额");
        }

        if(null == transactionNo){
            return ServerResponse.createByErrorMessage("未填写交易流水号");
        }


        //2018.9.14 上传凭证完直接变成待发货状态
//        int status = 20;
        //2018.9.17 凭证又改为需要审核了
        //int status = 10;

        //2018.9.17由
        //1.有orderNo 无transactionNo
        //2.无orderNo 有transactionNo
        //改成
        //1.有orderNo 有transactionNo
        //2.无orderNo 有transactionNo

        //先查如果有了不能进行插入
        if(null != orderNo && "".equals(orderNo) == false) {
            MallOrder mallOrder = orderMapper.selectByOrderNo(orderNo);
            if(null == mallOrder){
                return ServerResponse.createByErrorMessage("无该订单，请输入正确的订单号");
            }
//            if (mallOrder.getStatus() == 20) return ServerResponse.createByErrorMessage("您已处于待发货状态，请勿重复提交");
        }

        Integer count = mallPaymentVoucherMapper.selectCountByTransactionNo(transactionNo);
        if(count != 0) return ServerResponse.createByErrorMessage("该流水号的凭证已经通过，请勿重复操作");

        //orderMapper.changeOrderStatusByOrderNo(orderNo, status);

        MallPaymentVoucher mallPaymentVoucher = new MallPaymentVoucher();
        //交易流水号
        mallPaymentVoucher.setTransactionNo(transactionNo);
        mallPaymentVoucher.setCreateTime(new Date());
        mallPaymentVoucher.setFactPayment(dispositPay);
        mallPaymentVoucher.setVoucherImg(voucherImg);
        mallPaymentVoucher.setPaymentType(paymentType);
        mallPaymentVoucher.setUserId(userId);
        mallPaymentVoucher.setIsPay(1);
        mallPaymentVoucher.setIsDeposit(1);
        mallPaymentVoucher.setIsAdopt(0);
        mallPaymentVoucher.setOrderNo(orderNo);
        mallPaymentVoucherMapper.insert(mallPaymentVoucher);

        //2018.9.14 强行设定
        // 支付凭证已上传，订单状态变为发货中
        //回款直接加上 欠款直接减去
        //很有问题

        //2018.9.17
        //白写40行代码逻辑

        //1.维护总欠款表 unpayment
        //2.维护月度表  statement
//
//        MallPaymentUnpay mallPaymentUnpay = mallPaymentUnpayMapper.selectByPrimaryKey(customerId);
//        if(null == mallPaymentUnpay){
//            mallPaymentUnpay.setCustomerId(customerId);
//            mallPaymentUnpay.setUnpayPayment(new BigDecimal(0).subtract(dispositPay));
//            mallPaymentUnpayMapper.insert(mallPaymentUnpay);
//        }else{
//            mallPaymentUnpay.setCustomerId(customerId);
//            mallPaymentUnpay.setUnpayPayment(mallPaymentUnpay.getUnpayPayment().subtract(dispositPay));
//            mallPaymentUnpayMapper.updateByPrimaryKey(mallPaymentUnpay);
//        }
//
//        Calendar calendar = Calendar.getInstance();
//        int month = calendar.get(Calendar.MONTH);
//        int year = calendar.get(Calendar.YEAR);
//        //1.减少本月的欠款
//        //2.增加本月的还款
//        SysCustomerStatement sysCustomerStatement = sysCustomerStatementMapper.selectByCustomerIdAndDate(customerId, year, month + 1);
//        if(null == sysCustomerStatement){
//            BigDecimal lastUnpayment = new BigDecimal(0.0);
//            SysCustomerStatement lastSysCustomerStatement = sysCustomerStatementMapper.selectByCustomerIdAndDate(customerId, year, month);
//            if(null != lastSysCustomerStatement){
//                lastUnpayment = lastSysCustomerStatement.getThisMonthUnpayment();
//            }
//            //如果是空进行插入
//            sysCustomerStatement = new SysCustomerStatement();
//            sysCustomerStatement.setLastMonthUnpayment(lastUnpayment);
//            sysCustomerStatement.setThisMonthFufillmentPayment(new BigDecimal(0).subtract(dispositPay));
//            sysCustomerStatement.setThisMonthReturnPayment(dispositPay);
//            sysCustomerStatement.setYear(year);
//            sysCustomerStatement.setMonth(month + 1);
//            sysCustomerStatementMapper.insert(sysCustomerStatement);
//        }
//        sysCustomerStatementMapper.updateTwoPoint(dispositPay, year, month + 1);

        return ServerResponse.createBySuccess("交易凭证上传成功");
    }

    public ServerResponse<List<String>> getProductType() {

        Integer parentId = 6;
        List<String> typeList = mallAttrValueMapper.selectByParentId(6);
        return ServerResponse.createBySuccess(typeList);

    }


    /**
     * @Date 2018/12/5 15:57
     * @Param [userId, productPlanOrderJsonStr, shippingId, distCode, submitPerson, remark, transportId]
     * @return com.hmall.common.ServerResponse
     * @Description //TODO 重载方法 除了给计划下单要给常用商品下单
     */
    public ServerResponse createOrderByPlan(Integer userId, String productPlanOrderJsonStr, Integer shippingId, Integer distCode, Integer submitPerson, String remark, Integer transportId){

        return createOrderByPlan(userId, productPlanOrderJsonStr, shippingId, distCode, submitPerson, remark, transportId, "plan");
    }

    //通过计划单下定单
    public ServerResponse createOrderByPlan(Integer userId, String productPlanOrderJsonStr, Integer shippingId, Integer distCode, Integer submitPerson, String remark, Integer transportId, String type) {

        //是否是计划的
        //堆在一块，将来不好维护
        //2018/12/5
//        type = "1";
        Boolean checkPlan = "plan".equals(type);


            if(null == distCode) {
                return ServerResponse.createByErrorMessage("请输入正确的配送方式");
            }
            if(null == shippingId) {
                return ServerResponse.createByErrorMessage("请输入正确的收货地址");
            }

//           String testStr = "[{\"planItemId\":426,\"weight\":42}]";
//           String testStr = "[{\"planItemId\":497,\"weight\":200},{\"planItemId\":498,\"weight\":100}]";
//        productPlanOrderJsonStr = testStr;

//            JSONArray jsonArray =  JSONArray.fromObject(productPlanOrderJsonStr);
//
            List<PlanItemVo> planItemVoList = new ArrayList<>();
//            for(int i = 0; i < jsonArray.size(); i++){
//                PlanItemVo backOrderItemVo = (PlanItemVo) JSONObject.toBean((JSONObject) jsonArray.get(i), PlanItemVo.class);
//                planItemVoList.add(backOrderItemVo);
//            }
            Gson gson = new Gson();
            planItemVoList = gson.fromJson(productPlanOrderJsonStr, new TypeToken<List<PlanItemVo>>() {}.getType());

            //创建订单
//            Long orderNo = generateOrderNo();


            Integer dealerId = sysDeptCustomerMapper.selectDealerIdByUserId(userId);
            Long orderNo = NumberUtil.createOrderNo(dealerId);

            BigDecimal allPrice = new BigDecimal(0.0);
            for(PlanItemVo planItemVo : planItemVoList) {
                //先插入子

                MallProduct mallProduct;
                MallProductPlanItem mallProductPlanItem;
                String grade;
                Integer productId;
                if(checkPlan) {
                     mallProductPlanItem = mallProductPlanItemMapper.selectByPrimaryKey(planItemVo.getPlanItemId());
                    mallProduct = mallProductMapper.selectByProductId(mallProductPlanItem.getProductId());
                    grade = mallProductPlanItem.getGrade();
                    productId = mallProductPlanItem.getProductId();
                }else{
                    //用产品id替换计划id，为了前端方便......
                    //不推荐
                    mallProduct = mallProductMapper.selectByProductId(planItemVo.getPlanItemId());
                    grade = planItemVo.getGrade();
                    productId = planItemVo.getPlanItemId();
                }

                MallOrderItem mallOrderItem = new MallOrderItem();
                mallOrderItem.setCommentCheck(0);
                mallOrderItem.setCreateTime(new Date());


                mallOrderItem.setCurrentUnitPrice(mallProduct.getPrice());
                mallOrderItem.setGrade(grade);
                mallOrderItem.setOrderNo(orderNo);
                mallOrderItem.setProductId(productId);
                mallOrderItem.setProductImage(mallProduct.getMainImage());
                mallOrderItem.setQuantity(planItemVo.getWeight());
                String nameStr[] = mallProduct.getName().split(",");
                mallOrderItem.setProductModel(nameStr[2]);
                mallOrderItem.setProductName(mallProduct.getName());

                //如果是业务员提交需要有具体价格
                if(submitPerson == 2) {
                    mallOrderItem.setCurrentUnitPrice(planItemVo.getPrice() == null ? new BigDecimal(0) : planItemVo.getPrice());
                    if(planItemVo.getPrice() == null){
                        mallOrderItem.setTotalPrice(new BigDecimal(0));
                    }else {
                        mallOrderItem.setTotalPrice(planItemVo.getPrice().multiply(planItemVo.getWeight()));
                    }
                    } else {
                    //否则是产品挂牌价
                    mallOrderItem.setCurrentUnitPrice(mallProduct.getPrice());
                    mallOrderItem.setTotalPrice(mallProduct.getPrice().multiply(planItemVo.getWeight()));
                }

                mallOrderItem.setUserId(userId);
                mallOrderItem.setResidualQuantity(planItemVo.getWeight());
                mallOrderItem.setUpdateTime(new Date());
                BigDecimal bWeight = planItemVo.getWeight();

                //更新计划单余量
                //可以写在一个sql里面
                if(checkPlan) {
                    BigDecimal residualQuantity = mallProductPlanItemMapper.selectByPrimaryKey(planItemVo.getPlanItemId()).getResidualQuantity();
                    mallProductPlanItemMapper.updateResidualQuantity(residualQuantity.subtract(planItemVo.getWeight()), planItemVo.getPlanItemId());
                }
                mallOrderItem.setTotalPrice(mallProduct.getPrice().multiply(bWeight));
//                mallOrderItem.set
                allPrice = allPrice.add(mallProduct.getPrice().multiply(bWeight));
                try {
                    mallOrderItemMapper.insert(mallOrderItem);
                }catch (Exception e){
                    return ServerResponse.createByErrorMessage("订单详情创建失败");
                }
            }

            MallOrder mallOrder = new MallOrder();
            mallOrder.setOrderNo(orderNo);
            mallOrder.setUserId(userId);
            mallOrder.setShippingId(shippingId);
            mallOrder.setPayment(allPrice);
            mallOrder.setPaymentType(1);
            mallOrder.setTransportId(transportId);
//
//            //如果是业务员帮助创建，欠款增加
//            //2018/10/22 改到资金审核通过加欠款
            Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(userId);


            if(null == customerId){
                return ServerResponse.createByErrorMessage("该用户尚未绑定公司");
            }


            if(submitPerson == 2) {
                //2018/10/22 改
                mallOrder.setStatus(10);
            }else{
                mallOrder.setStatus(10);
            }


            mallOrder.setCreateTime(new Date());
            mallOrder.setDistcode(distCode);
            mallOrder.setIsSample(0);
            mallOrder.setSubmitPerson(submitPerson);
            mallOrder.setEnabled(1);
            mallOrder.setShopId(1);
            if(checkPlan) {
                mallOrder.setPlanCheck(1);
            }else{
                mallOrder.setPlanCheck(0);
            }
            mallOrder.setStatus1(0);
            mallOrder.setStatus2(0);
            mallOrder.setStatus3(0);
            mallOrder.setUpdateTime(new Date());
            mallOrder.setMessage(remark);
            mallOrder.setSendDate("");
            SysCustomer sysCustomer = sysCustomerMapper.selectByUserId(userId);
            mallOrder.setDealerId(sysCustomer.getDealerId());
            try {
                mallOrderMapper.insert(mallOrder);
            }catch (Exception e){
                return ServerResponse.createByErrorMessage("订单创建失败");
            }

            backPush(userId, orderNo, 2);

            return ServerResponse.createBySuccess("订单创建成功");
        }

    public ServerResponse<List<MallOrder>> getOrderByUser(Integer userId) {

        Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(userId);

            //找出状态为20的公司的最老的订单编号
        List<MallOrder> oldMallOrderList = orderMapper.selectOldestHavePay(customerId);

        List<MallOrder> mallOrderList = new ArrayList<>();
        for (MallOrder mallOrder : oldMallOrderList) {
            //Integer count = mallPaymentVoucherMapper.selectHaveExam(mallOrder.getOrderNo());
            mallOrderList.add(mallOrder);
        }
        return ServerResponse.createBySuccess(mallOrderList);
    }

    public UserDeviceVo testDevice(HttpServletRequest request) {
        Enumeration<String> names = request.getHeaderNames();
        while (names.hasMoreElements()) {
            String headerName = (String) names.nextElement();
            System.out.println("headerName===" + headerName);

            String headerValue = request.getHeader(headerName);//取出头信息内容
            System.out.println("headerValue===" + headerValue);
        }
        UserDeviceVo deviceVo=new UserDeviceVo();
        String agent=request.getHeader("user-agent");
        if(agent.toLowerCase().contains("mac")||agent.toLowerCase().contains("ios")){
            deviceVo.setDeviceName("苹果:"+agent.substring(0,agent.indexOf(")")));
            //deviceVo.setDeviceName("苹果");
        }else if(agent.toLowerCase().contains("android")){
            deviceVo.setDeviceName("安卓:"+agent.substring(0,agent.indexOf(")")));
        }else{
            deviceVo.setDeviceName("PC:"+agent.substring(0,agent.indexOf(")")));
        }

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        deviceVo.setIp(ip);
        return deviceVo;
    }



    //type 1 拿样
    //2 普通订单
    private String  backPush(Integer userId, Long orderNo, Integer type){
        //拿样消息推送给后台
        Map map = new HashMap();
        map.put("customerUserId", userId +"");
        map.put("status", type + "");
        map.put("value", orderNo + "");
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        map.put("date", (new Date().toString()));

        String url = EnvUtil.getPreUrl("mall");
        url += "/jpush/backPush";
        return HttpClientUtil.doPostWithParam(url, map);

    }


}


